import React, { useState } from 'react';
import { Modal } from 'antd';

interface Props {
  okCallback?: () => void;
  cancelCallback?: () => void;
}

interface openProps {
  title?: string
  modalText?: string
}

export default function useAsyncModal({ okCallback, cancelCallback }: Props) {
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [textContent, setTextContent] = useState<openProps>({ title: '', modalText: '' })

  const openAsyncModal = ({ title, modalText }: openProps) => {
    setTextContent({ title, modalText });
    setOpen(true);
  }

  const handleOk = async () => {
    if (okCallback) {
      setConfirmLoading(true);
      await okCallback?.()
      setConfirmLoading(false);
    } else {
      setOpen(false);
    }
  };

  const handleCancel = () => {
    cancelCallback?.()
    setOpen(false);
  };

  const asyncModal = () => {
    return (
      <Modal
        title={textContent?.title}
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <p>{textContent?.modalText}</p>
      </Modal>
    )
  }

  return [openAsyncModal, asyncModal];
}
